import { Player } from "@minecraft/server";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { ParkourGame } from "@/parkour/parkourGame";
import { PKPreParingState } from "../state";

export class GameStarter extends GameComponent<PKPreParingState> {
    override onAttach(): void {
        //按钮订阅
        this.subscribe(
            Game.events.buttonPush,
            (t) => {
                if (!(t.source instanceof Player)) return;
                if (this.state.isCounting) return;
                //检查有无游戏正在运行
                if (Game.manager.hasGame(ParkourGame)) {
                    t.source.sendMessage(
                        "游戏无法开始，请等待正在进行的游戏结束"
                    );
                    return;
                }
                //检查人数
                if (this.state.checkPlayers()) {
                    this.startCountDown();
                } else {
                    t.source.sendMessage("人数不足，无法开始");
                }
            },
            {
                dimensionId: DimensionIds.Overworld,
                loc: [726, -58, 431],
            }
        );
    }

    /** 开始倒计时 */
    startCountDown() {
        this.state.isCounting = true;

        const showTitle = (text: string, subtitle?: string) => {
            this.state.region.getPlayersInRegion().forEach((p) =>
                p.onScreenDisplay.setTitle(text, {
                    fadeInDuration: 5,
                    fadeOutDuration: 5,
                    stayDuration: 20,
                    subtitle: subtitle,
                })
            );
        };

        const playSound = (soundId: string, pitch?: number) => {
            this.state.region
                .getPlayersInRegion()
                .forEach((p) => p.playSound(soundId, { pitch }));
        };

        const colors = ["§r", "§r", "§c", "§b", "§d"];
        const sounds = [
            "note.hat",
            "note.hat",
            "note.bass",
            "note.harp",
            "note.pling",
        ];

        this.runner.run(async (r) => {
            const steps: (() => void | Promise<void>)[] = [];

            for (let i = 5; i >= 1; i--) {
                const color = colors[(5 - i) % colors.length];
                const sound = sounds[(5 - i) % sounds.length];

                steps.push(() => {
                    showTitle(`${color}游戏即将开始`, `${color}${i}`);
                    playSound(sound);
                });
                steps.push(() => r.wait(20));
            }

            await r.runSteps(steps);
            r.do(() => this.state.startGame());
        });
    }
}
